<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单 - 鲜时蔬</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <!-- 引入vue-qriously生成二维码 -->
    <script src="../../js/vue-qriously.js"></script>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .personal-center {
            display: flex;
            gap: 20px;
        }

        /* 侧边栏 */
        .sidebar {
            width: 250px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .user-profile {
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid #eee;
        }

        .user-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: #27ae60;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin: 0 auto 10px;
        }

        .user-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .user-email {
            color: #999;
            font-size: 14px;
        }

        .menu {
            padding: 10px 0;
        }

        .menu-item {
            padding: 12px 20px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .menu-item:hover {
            background: #f5f7fa;
        }

        .menu-item.active {
            background: #ecf5ff;
            color: #27ae60;
            border-right: 3px solid #27ae60;
        }

        /* 主内容区 */
        .main-content {
            flex: 1;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .content-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
        }

        .content-body {
            padding: 20px;
        }

        /* 订单列表 */
        .order-list {
            margin-top: 20px;
        }

        .order-card {
            border: 1px solid #ebeef5;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }

        .order-header {
            padding: 15px 20px;
            background-color: #f5f7fa;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .order-info {
            display: flex;
            gap: 30px;
        }

        .order-status {
            font-weight: bold;
        }

        .status-pending {
            color: #e6a23c;
        }

        .status-shipped {
            color: #409eff;
        }

        .status-completed {
            color: #67c23a;
        }

        .status-cancelled {
            color: #909399;
        }

        .order-items {
            padding: 20px;
        }

        .item-row {
            display: flex;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .item-row:last-child {
            border-bottom: none;
        }

        .item-image {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            margin-right: 15px;
        }

        .item-details {
            flex: 1;
        }

        .item-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .item-spec {
            color: #999;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .item-price {
            color: #e74c3c;
            font-weight: bold;
        }

        .item-quantity {
            width: 100px;
            text-align: center;
        }

        .item-shipping {
            width: 120px;
            text-align: center;
        }

        .shipping-status {
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .shipping-pending {
            background-color: #fdf6ec;
            color: #e6a23c;
        }

        .shipping-shipped {
            background-color: #ecf5ff;
            color: #409eff;
        }

        .order-footer {
            padding: 15px 20px;
            background-color: #f5f7fa;
            border-top: 1px solid #ebeef5;
            display: flex;
            justify-content: flex-end;
            align-items: center;
        }

        .order-total {
            font-size: 18px;
            font-weight: bold;
            margin-right: 20px;
        }

        .order-actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            border: none;
            font-size: 14px;
        }

        .btn-primary {
            background-color: #27ae60;
            color: white;
        }

        .btn-primary:hover {
            background-color: #219653;
        }

        .btn-secondary {
            background-color: #909399;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #606266;
        }

        .btn-disabled {
            background-color: #c0c4cc;
            cursor: not-allowed;
        }

        .empty-orders {
            text-align: center;
            padding: 50px;
            color: #999;
        }

        .loading {
            text-align: center;
            padding: 50px;
        }

        /* 订单操作记录 */
        .order-activities {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #eee;
        }

        .activity-title {
            font-weight: bold;
            margin-bottom: 10px;
        }

        .activity-item {
            display: flex;
            padding: 8px 0;
            font-size: 14px;
        }

        .activity-time {
            width: 160px;
            color: #999;
        }

        .activity-desc {
            flex: 1;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .personal-center {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
            }

            .item-row {
                flex-direction: column;
                gap: 10px;
            }

            .order-info {
                flex-direction: column;
                gap: 10px;
            }

            .order-footer {
                flex-direction: column;
                gap: 15px;
            }

            .order-total {
                margin-right: 0;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <div class="personal-center">
            <!-- 侧边栏 -->
            <div class="sidebar">
                <div class="user-profile">
                    <div class="user-avatar">
                        {{ userInfo.nickName ? userInfo.nickName.charAt(0) : userInfo.userName.charAt(0) }}
                    </div>
                    <div class="user-name">{{ userInfo.nickName || userInfo.userName }}</div>
                    <div class="user-email">{{ userInfo.email || '未设置邮箱' }}</div>
                </div>
                <div class="menu">
                    <div class="menu-item" :class="{ active: activeMenu === 'profile' }"
                         @click="activeMenu = 'profile'">个人信息
                    </div>
                    <div class="menu-item" :class="{ active: activeMenu === 'orders' }" @click="activeMenu = 'orders'">
                        我的订单
                    </div>
                    <div class="menu-item" :class="{ active: activeMenu === 'address' }"
                         @click="activeMenu = 'address'">收货地址
                    </div>
                    <div class="menu-item" :class="{ active: activeMenu === 'merchant' }"
                         @click="activeMenu = 'merchant'">注册商家
                    </div>
                    <div class="menu-item" :class="{ active: activeMenu === 'security' }"
                         @click="activeMenu = 'security'">账号安全
                    </div>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="main-content">
                <div class="content-header">
                    <h2>{{ menuTitles[activeMenu] }}</h2>
                </div>

                <div class="content-body">
                    <!-- 我的订单模块 -->
                    <div v-if="activeMenu === 'orders'">
                        <div v-if="loading" class="loading">
                            <el-spinner style="margin: 50px auto;"></el-spinner>
                            <p>正在加载订单信息...</p>
                        </div>

                        <div v-else>
                            <div v-if="orders.length === 0" class="empty-orders">
                                <h3>暂无订单</h3>
                                <p>您还没有购买任何商品</p>
                                <el-button type="primary" @click="goToShopping" style="margin-top: 20px;">
                                    去购物
                                </el-button>
                            </div>

                            <div v-else class="order-list">
                                <div v-for="order in orders" :key="order.orderId" class="order-card">
                                    <div class="order-header">
                                        <div class="order-info">
                                            <div>订单编号: {{ order.orderNo }}</div>
                                            <div>下单时间: {{ formatDate(order.createTime) }}</div>
                                            <div>订单金额: <span style="color: #e74c3c;">¥{{ order.totalAmount }}</span></div>
                                        </div>
                                        <div class="order-status" :class="getOrderStatusClass(order)">
                                            {{ getOrderStatusText(order) }}
                                        </div>
                                    </div>

                                    <div class="order-items">
                                        <div v-for="item in order.orderItems" :key="item.itemId" class="item-row">
<!--                                            <div class="item-image" style="background-color: #f5f7fa; display: flex; align-items: center; justify-content: center;">-->
<!--                                                <i class="el-icon-shopping-bag" style="font-size: 24px; color: #999;"></i>-->
<!--                                            </div>-->
                                            <!-- 修改 item-image 部分 -->
                                            <div class="item-image">
                                                <img v-if="item.imageUrl" :src="item.imageUrl" :alt="item.productName"
                                                     @error="handleImageError($event)"
                                                     style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;">
                                                <i v-else class="el-icon-shopping-bag" style="font-size: 24px; color: #999;"></i>
                                            </div>

                                            <div class="item-details">
                                                <div class="item-name">{{ item.productName }}</div>
                                                <div class="item-spec">{{ item.productSpec || '默认规格' }}</div>
                                                <div class="item-price">¥{{ item.salePrice }}</div>
                                            </div>
                                            <div class="item-quantity">
                                                数量: {{ item.orderQuantity }}
                                            </div>
                                            <div class="item-shipping">
                                                <span class="shipping-status"
                                                      :class="item.sortingStatus === '1' ? 'shipping-shipped' : 'shipping-pending'">
                                                    {{ item.sortingStatus === '1' ? '已发货' : '未发货' }}
                                                </span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="order-activities" v-if="order.orderActs && order.orderActs.length > 0">
                                        <div class="activity-title">订单操作记录</div>
                                        <div v-for="act in order.orderActs" :key="act.orderactid" class="activity-item">
                                            <div class="activity-time">{{ formatDate(act.cztime) }}</div>
                                            <div class="activity-desc">{{ getOrderActText(act.actno) }} - {{ act.remark || '' }}</div>
                                        </div>
                                    </div>

                                    <div class="order-footer">
                                        <div class="order-total">
                                            合计: <span style="color: #e74c3c;">¥{{ order.totalAmount }}</span>
                                        </div>
                                        <div class="order-actions">
                                            <!-- 去支付按钮 -->
                                            <el-button
                                                    v-if="order.orderActs && order.orderActs.length > 0 && order.orderActs[0].actno === 0"
                                                    type="primary"
                                                    size="small"
                                                    @click="goToPay(order)">
                                                去支付
                                            </el-button>
                                            <el-button
                                                    v-if="canConfirmReceipt(order)"
                                                    type="primary"
                                                    size="small"
                                                    @click="confirmReceipt(order)">
                                                确认收货
                                            </el-button>
                                            <el-button
                                                    type="info"
                                                    size="small"
                                                    @click="viewOrderDetail(order.orderId)">
                                                查看详情
                                            </el-button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 其他菜单内容 -->
                    <div v-else>
                        <p>这里是{{ menuTitles[activeMenu] }}的内容</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- 支付二维码弹窗 -->
    <el-dialog
            title="微信扫码支付"
            :visible.sync="showQRDialog"
            width="400px"
            :before-close="handleClose">
        <div class="qrcode-container">
            <div style="margin-bottom: 15px;">支付金额: ¥{{ totalAmount }}</div>
            <qriously v-if="codeUrl" :value="codeUrl" :size="256" />
            <div class="qrcode-status">
                订单状态: {{ payStatus }}
            </div>
            <div v-if="payStatus === '支付成功'" class="success-message">
                支付成功！
            </div>
        </div>
    </el-dialog>

</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                activeMenu: 'orders',
                userInfo: {},
                menuTitles: {
                    profile: '个人信息',
                    orders: '我的订单',
                    address: '收货地址',
                    merchant: '注册商家',
                    security: '账号安全'
                },
                orders: [],
                loading: true,
                showQRDialog: false,
                codeUrl: '',
                payStatus: '等待支付',
                paymentSuccess: false,
            }
        },
        mounted() {
            this.loadUserInfo();

        },
        methods: {
            // 加载用户信息
            loadUserInfo() {
                axios.get('/vegetablemarketexpress/user/checkLoginStatus', {withCredentials: true})
                    .then(response => {
                        if (response.data.code === 200) {
                            this.userInfo = response.data.data;
                            this.loadOrders(); // 加载用户信息后加载订单
                        } else {
                            // 用户未登录，跳转至登录页
                            window.location.href = '/vegetablemarketexpress/html/front/login.html';
                        }
                    })
                    .catch(error => {
                        console.error('加载用户信息失败:', error);
                        this.$message.error('加载用户信息失败');
                    });
            },

            loadOrders() {
                this.loading = true;
                axios.get('/vegetablemarketexpress/order/getUserOrders', {withCredentials: true})
                    .then(response => {
                        if (response.data.code === 200) {
                            this.orders = response.data.data.orders || [];
                            console.log("订单数据:", this.orders);
                        } else {
                            this.$message.error('加载订单失败: ' + (response.data.message || '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('加载订单失败:', error);
                        this.$message.error('加载订单失败，请重试');
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },



            // 格式化日期
            formatDate(date) {
                if (!date) return '';
                return new Date(date).toLocaleString('zh-CN');
            },

            // 获取订单状态文本（基于orderact表中的状态）
            getOrderStatusText(order) {
                // 确保 orderActs 存在且不为空
                if (order && order.orderActs && Array.isArray(order.orderActs) && order.orderActs.length > 0) {
                    // 获取最新的订单操作记录
                    const latestAct = order.orderActs[0];
                    // 确保 latestAct 和 actno 存在
                    if (latestAct && latestAct.actno !== undefined) {
                        const statusMap = {
                            0: '待支付',
                            1: '已支付（待发货）',
                            2: '已发货（待接收）',
                            3: '已完成',
                            4: '已关闭',
                            5: '无效订单'
                        };
                        return statusMap[latestAct.actno] || '未知状态';
                    }
                }
                // 如果没有操作记录，根据商品发货状态判断
                if (order && order.orderItems && Array.isArray(order.orderItems)) {
                    const shippedItems = order.orderItems.filter(item => item.sortingStatus === '1');
                    if (shippedItems.length === order.orderItems.length) {
                        return '已发货（待接收）';
                    }
                }
                return '未知状态';
            },


            // 获取订单状态样式类
            getOrderStatusClass(order) {
                // 通过orderActs获取最新的订单状态
                if (order && order.orderActs && Array.isArray(order.orderActs) && order.orderActs.length > 0) {
                    const latestAct = order.orderActs[0]; // 获取最新的操作记录
                    const classMap = {
                        0: 'status-pending',
                        1: 'status-pending',
                        2: 'status-shipped',
                        3: 'status-completed',
                        4: 'status-cancelled',
                        5: 'status-cancelled',
                        10: 'status-pending',
                    };
                    return classMap[latestAct.actno] || '';
                }

                // 如果没有操作记录，根据商品发货状态判断
                if (order && order.orderItems && Array.isArray(order.orderItems)) {
                    const shippedItems = order.orderItems.filter(item => item.sortingStatus === '1');
                    if (shippedItems.length === order.orderItems.length) {
                        return 'status-shipped';
                    }
                }

                return '';
            },


            // 获取订单操作记录文本
            getOrderActText(actno) {
                const actMap = {
                    0: '待支付',
                    1: '已支付',
                    2: '已发货',
                    3: '已完成',
                    4: '已关闭',
                    5: '无效订单',
                    10: '部分发货提示'
                };
                return actMap[actno] || '未知操作';
            },

            // 判断是否可以确认收货（订单状态为已发货）
            canConfirmReceipt(order) {
                // 确保 orderActs 存在且不为空
                if (order && order.orderActs && Array.isArray(order.orderActs) && order.orderActs.length > 0) {
                    // 获取最新的订单操作记录
                    const latestAct = order.orderActs[0];
                    // 确保 latestAct 和 actno 存在
                    if (latestAct && latestAct.actno !== undefined) {
                        return latestAct.actno === 2; // 2-已发货（待接收）
                    }
                }

                // 如果没有操作记录，根据商品发货状态判断
                if (order && order.orderItems && Array.isArray(order.orderItems)) {
                    const shippedItems = order.orderItems.filter(item => item.sortingStatus === '1');
                    if (shippedItems.length === order.orderItems.length) {
                        return true; // 所有商品都已发货，可以确认收货
                    }
                }

                return false;
            },


            // 在 confirmReceipt 方法中添加调试信息
            confirmReceipt(order) {
                console.log("尝试确认收货:", order);

                this.$confirm('确认收货后订单将变为已完成状态，是否确认收货？', '确认收货', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/vegetablemarketexpress/order/confirmReceipt', {
                        orderId: order.orderId,
                        orderNo: order.orderNo
                    }, {withCredentials: true})
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('确认收货成功');
                                this.loadOrders(); // 重新加载订单
                            } else {
                                this.$message.error('确认收货失败: ' + (response.data.message || '未知错误'));
                            }
                        })
                        .catch(error => {
                            console.error('确认收货失败:', error);
                            this.$message.error('确认收货失败，请重试');
                        });
                }).catch(() => {
                    // 取消确认
                });
            },


            // 查看订单详情
            viewOrderDetail(orderId) {
                // 这里可以跳转到订单详情页面，或者显示弹窗详情
                this.$message.info('查看订单详情功能待实现，订单ID: ' + orderId);
            },

            // 去购物
            goToShopping() {
                window.location.href = '/vegetablemarketexpress/html/front/index.html';
            },
            handleImageError(event) {
                event.target.src = '/static/images/no-image.png';
            },

            // 修改 goToPay 方法
            goToPay(order) {
                // 设置订单信息
                this.orderNo = order.orderNo;
                this.totalAmount = order.totalAmount;

                // 生成支付二维码
                this.generatePaymentQRCode(order.orderNo);
            },
            // 修改 generatePaymentQRCode 方法
            generatePaymentQRCode(orderNo) {
                // 使用新的接口，只传递订单编号
                axios.post('/vegetablemarketexpress/order/getNativeCodeUrlByOrderNo?orderNo=' + orderNo, {}, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.codeUrl = response.data.data.code_url;
                            this.showQRDialog = true;
                            this.startQueryPayStatus();
                        } else {
                            this.$message.error('获取支付二维码失败');
                        }
                    })
                    .catch(error => {
                        console.error('生成支付二维码失败:', error);
                        this.$message.error('网络错误，生成支付二维码失败');
                    });
            },

            // 开始轮询支付status
            startQueryPayStatus() {
                // 清除之前的定时器
                if (this.timer) {
                    clearInterval(this.timer);
                }

                // 每3秒查询一次支付status
                this.timer = setInterval(() => {
                    this.queryPayStatus();
                }, 3000);
            },

// 查询支付status
            queryPayStatus() {
                if (!this.orderNo) return;

                axios.get('/vegetablemarketexpress/order/getPayStatus/' + this.orderNo, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.payStatus = response.data.data.trade_state_desc;

                            if (this.payStatus === '支付成功') {
                                // 支付成功，更新订单状态
                                this.updateOrderStatus();
                                // 关闭定时器
                                clearInterval(this.timer);
                                this.showQRDialog = false;
                                // 提示用户支付成功
                                this.$message.success('支付成功！');
                            }
                        }
                    })
                    .catch(error => {
                        console.error('查询支付状态失败:', error);
                    });
            },

            // 更新订单status
            updateOrderStatus() {
                const updateData = {
                    orderNo: this.orderNo,
                    status: 1 // 1-已支付
                };

                axios.post('/vegetablemarketexpress/order/updateStatus', updateData, {withCredentials: true})
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            console.log('订单状态更新成功');
                            // 重新加载订单列表
                            this.loadOrders();
                        } else {
                            console.error('订单状态更新失败');
                        }
                    })
                    .catch(error => {
                        console.error('更新订单状态失败:', error);
                    });
            },
            // 关闭对话框
            handleClose(done) {
                this.$confirm('确认关闭支付窗口？')
                    .then(_ => {
                        done();
                        if (this.timer) {
                            clearInterval(this.timer);
                        }
                    })
                    .catch(_ => {});
            },

        }
    });
</script>
</body>
</html>
